package com.goodving.guli.activity;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.goodving.guli.R;
import com.goodving.guli.bt.BLEService;
import com.goodving.guli.bt.C0668a;
import com.goodving.guli.bt.C0708b;
import com.goodving.guli.bt.C0715c;
import com.goodving.guli.bt.DimPanelFragment;
import com.goodving.guli.bt.Utils;
import com.goodving.guli.bt.eventbus.EventDeviceBoundState;
import com.goodving.guli.bt.model.C3911i;
import com.goodving.guli.bt.profile.scale.C1798h;
import com.goodving.guli.bt.profile.scale.C3900g;
import com.goodving.guli.bt.profile.scale.C3907e;
import com.goodving.guli.bt.profile.scale.C3923a;
import com.goodving.guli.bt.profile.scale.FilterBleDevInfo;
import com.goodving.guli.bt.profile.scale.GuliLog;
import com.goodving.guli.bt.profile.scale.ScaleWeightInfo;
import com.goodving.guli.bt.profile.scale.WeightHwInfo;
import com.goodving.guli.bt.profile.scale.WeightProfile;
import com.goodving.guli.bt.profile.scale.XMBLEManager;
import com.goodving.guli.bt.profile.scale.XMLeScanCenter;
import com.goodving.guli.model.BtDevice;
import com.goodving.guli.model.DeviceSource;
import com.goodving.guli.model.Keeper;
import com.goodving.guli.server.C1327j;
import com.goodving.guli.server.WebAPI;
import com.goodving.guli.server.WebResponse;
import com.goodving.guli.utility.Constants;
import com.goodving.guli.utility.gulihardware.Constant;
import com.goodving.guli.view.C3247b;
import com.goodving.guli.view.C3657a;
import com.goodving.guli.view.C4220a;
import com.loopj.android.http.AsyncHttpResponseHandler;

import java.util.ArrayList;
import java.util.HashMap;

import cn.com.smartdevices.bracelet.chart.LinePieChartView;
import cz.msebera.android.httpclient.Header;
import de.greenrobot.event.EventBus;

/**
 * Created by Administrator on 2015/11/25 0025.
 */
public class SearchWeightScaleActivity extends SystemBarTintActivity implements View.OnClickListener, C1798h {
    private static final String TAG = "search weight";
    private static final int f9197b = 8193;
    private static final int f9198c = 1;
    private static final int f9199d = 2;
    private static final int f9200e = 3;
    private static final int f9201f = 5;
    private static final int f9202g = 60000;
    private static final int f9203h = 60000;
    private ScaleWeightInfo mWeightInfoA;
    private TextView mScaleValue;
    private ImageView mScaleSmile;
    private boolean f9207D;
    private HashMap<String, String> f9208E;
    private final XMLeScanCenter mScanCenter;
    private FilterBleDevInfo mFilterWeightInfo; //FilterBleDevInfo
    private LinePieChartView f9211i;
    private TextView mExitBind;
    private DevListAdapter mDevListAdapter;
    private View mDevView;
    private ListView mDevListView;
    private View mSearchView;
    private TextView mBindDevTitle;
    private TextView mBindDevTip;
    private TextView mDevNoResponse;
    private ImageView mDevSearchIcon;
    private ArrayList<BtDevice> mBtDevList;
    private Handler mHandler;
    private int f9223u;
    private Activity mActivity;
    private boolean f9225w;
    private BluetoothDevice mBleDev;
    private BroadcastReceiver f9227y;
    private ScaleWeightInfo mWeightInfo;

    class DevListAdapter extends BaseAdapter {
        private ArrayList<BtDevice> mBtDevArrayList;
        private Context mContext;

        public DevListAdapter(Context context, ArrayList<BtDevice> arrayList) {
            this.mContext = context;
            this.mBtDevArrayList = arrayList;
        }

        public int getCount() {
            return this.mBtDevArrayList == null ? 0 : this.mBtDevArrayList.size();
        }

        public Object getItem(int i) {
            return Integer.valueOf(i);
        }

        public long getItemId(int i) {
            return (long) i;
        }

        public View getView(int i, View view, ViewGroup viewGroup) {
            View inflate = LayoutInflater.from(this.mContext).inflate(R.layout.search_device_item, null);
            BtDevice btDevice = (BtDevice) this.mBtDevArrayList.get(i);
            TextView mTextMac = (TextView) inflate.findViewById(R.id.searched_device_item_mac_tv);
            TextView mTextSignal = (TextView) inflate.findViewById(R.id.searched_device_item_signal_tv);
            ((RelativeLayout.LayoutParams) inflate.findViewById(R.id.searched_device_item_signal_bar).getLayoutParams()).rightMargin = (-btDevice.signal) * 5;
            inflate.invalidate();
            String address = btDevice.device.getAddress();
            mTextMac.setText(address.substring(address.length() - "MM:AA:CC".length(), address.length()));
            mTextSignal.setText(this.mContext.getString(R.string.signal_strength) + btDevice.signal);
            return inflate;
        }
    }

    public SearchWeightScaleActivity() {
        this.mWeightInfoA = null;
        this.mScanCenter = XMLeScanCenter.getInstance();
        this.mFilterWeightInfo = null;
    }

    class MyHandler extends Handler {
        final /* synthetic */ SearchWeightScaleActivity mSearchWeightScaleActivity;

        MyHandler(SearchWeightScaleActivity searchWeightScaleActivity) {
            this.mSearchWeightScaleActivity = searchWeightScaleActivity;
        }

        public void handleMessage(Message message) {
            switch (message.what) {
                case 1 /*1*/:
                    Utils.m7991a(this.mSearchWeightScaleActivity.mActivity);
                    this.mSearchWeightScaleActivity.setResult(-1);
                    this.mSearchWeightScaleActivity.finish();
                    C0668a.m8126a(this.mSearchWeightScaleActivity.mActivity, C0668a.fX);
                    break; // get this from decompile website instead of JADX
                case 2 /*2*/:
                case 5 /*5*/:
                    C3247b.m22928a(this.mSearchWeightScaleActivity.mActivity, (int) R.string.bind_weight_fail, 1).show();
                    Utils.m7991a(this.mSearchWeightScaleActivity.mActivity);
                    this.mSearchWeightScaleActivity.m14054i();
                    C0668a.m8126a(this.mSearchWeightScaleActivity.mActivity, C0668a.fW);
                    break; // get this from decompile website instead of JADX
                case 3 /*3*/:
                    this.mSearchWeightScaleActivity.stopBleScan();
                    this.mSearchWeightScaleActivity.m14056j();
                    C0668a.m8126a(this.mSearchWeightScaleActivity.mActivity, C0668a.fV);
                    break; // get this from decompile website instead of JADX
                default:
                    break; // get this from decompile website instead of JADX
            }
        }
    }

    class WeightGattUpdateReceiver extends BroadcastReceiver // dx
    {

        final SearchWeightScaleActivity thisSearchWeightScaleActivity;

        WeightGattUpdateReceiver(SearchWeightScaleActivity searchweightscaleactivity)
        {
            super();
            thisSearchWeightScaleActivity = searchweightscaleactivity;
        }

        public void onReceive(Context context, Intent intent)
        {
            int i = intent.getIntExtra(BLEService.mStrExtraParam, -1);
            thisSearchWeightScaleActivity.m14034a(i);
        }
    }

    private void m14033a() {
        this.mHandler = new MyHandler(this);
        this.f9227y = new WeightGattUpdateReceiver(this);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BLEService.mStrWeightConStatusChanged);
        registerReceiver(this.f9227y, intentFilter);
    }

    private void m14034a(int i) {
        GuliLog.tracePrintInfo(TAG, "connect status:" + i);
        if (i == f9198c) {
            this.mHandler.sendEmptyMessage(f9199d);
        } else if (i == f9199d) {
        } else {
            if (i == 0) {
                this.mHandler.sendEmptyMessage(f9199d);
            } else if (i == 4) {
                this.mHandler.sendEmptyMessage(f9199d);
            } else if (i == f9200e) {
                m14048f();
            }
        }
    }

    private void m14035a(BluetoothDevice bluetoothDevice) {
        GuliLog.tracePrintInfo(TAG, "connect :" + bluetoothDevice.getAddress());
        XMBLEManager.m25150a(bluetoothDevice, true);
        this.mHandler.sendEmptyMessageDelayed(f9201f, 60000);//TBDC4125d.f20546g);
    }

    class dy implements AdapterView.OnItemClickListener {
        final /* synthetic */ SearchWeightScaleActivity mSearchWeightScaleActivity;

        dy(SearchWeightScaleActivity searchWeightScaleActivity) {
            this.mSearchWeightScaleActivity = searchWeightScaleActivity;
        }

        public void onItemClick(AdapterView<?> adapterView, View view, int i, long j) {
            this.mSearchWeightScaleActivity.stopBleScan();
            if (this.mSearchWeightScaleActivity.f9223u != -1) {
                this.mSearchWeightScaleActivity.m14053h();
                DeviceSource.unbindWeight();
            }
            this.mSearchWeightScaleActivity.f9223u = i;
            this.mSearchWeightScaleActivity.mBleDev = ((BtDevice) this.mSearchWeightScaleActivity.mBtDevList.get(i)).device;
            this.mSearchWeightScaleActivity.m14035a(this.mSearchWeightScaleActivity.mBleDev);
            this.mSearchWeightScaleActivity.f9225w = false;
            this.mSearchWeightScaleActivity.m14060a(this.mSearchWeightScaleActivity.f9225w);
            this.mSearchWeightScaleActivity.applyStatusBarTintAuto();
        }
    }

    private void initView() {
        this.mDevListAdapter = new DevListAdapter(this, this.mBtDevList);
        this.mDevView = findViewById(R.id.search_single_device_list_area);
        this.mHomeBack.setText(R.string.weight_device_list);
        this.mDevListView = (ListView) findViewById(R.id.device_list_lv);
        this.mDevListView.setAdapter(this.mDevListAdapter);
        this.mDevListView.setOnItemClickListener(new dy(this));
        this.mSearchView = findViewById(R.id.search_single_area);
        this.mBindDevTitle = (TextView) findViewById(R.id.search_devices_title);
        this.mBindDevTip = (TextView) findViewById(R.id.search_devices_info);
        this.mBindDevTitle.setText(R.string.find_weight_scale_info);
        this.mBindDevTip.setText(C3657a.f18328f);
        this.mExitBind = (TextView) findViewById(R.id.search_devices_exit);
        this.mExitBind.setText(Html.fromHtml("<u>" + getString(R.string.donot_bind) + "</u>"));
        this.mExitBind.setOnClickListener(this);
        this.mExitBind.setVisibility(View.VISIBLE);
        this.mDevNoResponse = (TextView) findViewById(R.id.search_devices_not_response);
        this.mDevNoResponse.setOnClickListener(this);
        this.mDevNoResponse.setVisibility(View.GONE);
        this.mDevSearchIcon = (ImageView) findViewById(R.id.search_devices_mili_icon);
        this.mDevSearchIcon.setImageResource(R.drawable.gu_logo);
        this.f9211i = (LinePieChartView) findViewById(R.id.searching_pie_chart);
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) this.f9211i.getLayoutParams();
        layoutParams.width = (int) getResources().getDimension(R.dimen.draw_weight_icon_w);
        layoutParams.height = (int) getResources().getDimension(R.dimen.draw_weight_icon_w);
        this.f9211i.setMode(4);
        this.f9211i.d_();
        this.mScaleValue = (TextView) findViewById(R.id.search_devices_weight_value);
        this.mScaleSmile = (ImageView) findViewById(R.id.search_devices_weight_smile);
        findViewById(R.id.search_single_frame).setBackgroundColor(getResources().getColor(R.color.blue));
    }

    private boolean m14043c() {
        BluetoothAdapter defaultAdapter = BluetoothAdapter.getDefaultAdapter();
        if (defaultAdapter == null || defaultAdapter.isEnabled()) {
            return true;
        }
        startActivityForResult(new Intent("android.bluetooth.adapter.action.REQUEST_ENABLE"), f9197b);
        return false;
    }

    private void startBleScan() {
        GuliLog.tracePrintInfo(TAG, "----------start scan------------");
        this.mScanCenter.startScan(this.mActivity, this.mFilterWeightInfo);
    }

    private void stopBleScan() {
        GuliLog.tracePrintInfo(TAG, "----------stop scan------------");
        this.mScanCenter.m25373a(this.mFilterWeightInfo);
        if (this.mHandler != null) {
            this.mHandler.removeMessages(f9200e);
            this.mHandler.removeMessages(f9201f);
            return;
        }
        GuliLog.tracePrintInfo(TAG, "mHandler is NULL!!!!!!!!!!!!!!!!!");
    }

    private void m14048f() {
        C3247b.m22928a(this.mActivity, (int) R.string.bind_weight_ok, 3).show();
        C3911i c3911i = null;
        WeightProfile i = XMBLEManager.m25164i();
        if (i != null) {
            c3911i = i.m25532z();
        }
        WeightHwInfo weightHwInfo = new WeightHwInfo();
        weightHwInfo.name = this.mBleDev.getName();
        weightHwInfo.address = this.mBleDev.getAddress();
        if (c3911i != null) {
            weightHwInfo.fwVersion = c3911i.f19720c;
            weightHwInfo.deviceId = c3911i.f19718a;
        }
        DeviceSource.bindWeight(weightHwInfo);
        if (Utils.m8084k(this.mActivity)) {
            m14051g();
        }
        if (this.mWeightInfoA != null) {
            EventBus.getDefault().post(this.mWeightInfoA);
        }
        this.mHandler.sendEmptyMessageDelayed(f9198c, 0);
        EventBus.getDefault().post(new EventDeviceBoundState(f9198c, f9198c));
    }

    class dz extends AsyncHttpResponseHandler {
        final /* synthetic */ SearchWeightScaleActivity f10020a;

        dz(SearchWeightScaleActivity searchWeightScaleActivity) {
            this.f10020a = searchWeightScaleActivity;
        }

        public void onFailure(int i, Header[] headerArr, byte[] bArr, Throwable th) {
            Keeper.setSyncWeightInfoToServer(1);
        }

        public void onSuccess(int i, Header[] headerArr, byte[] bArr) {
            if (bArr != null) {
                String str = new String(bArr);
                GuliLog.tracePrintInfo("search weight", "updateBindedWeightInfo result:" + str);
                if (WebResponse.getWebResponse(this.f10020a.getApplicationContext(), str).m11659c()) {
                    Keeper.setSyncWeightInfoToServer(2);
                }
            }
        }
    }

    private void m14051g() {
        C1327j.m11576a(this.mActivity, WebAPI.m11583a(getApplicationContext(), (int) f9198c), new dz(this), true);
    }

    private void m14053h() {
        XMBLEManager.m25163h();
    }

    private void m14054i() {
        stopBleScan();
        m14053h();
        setResult(-1);
        Intent intent = new Intent(this.mActivity, MultiDevicesErrActivity.class);
        intent.setFlags(67108864);
        intent.putExtra(Utils.f3493a, Utils.f3496d);
        startActivity(intent);
        finish();
    }

    private void m14056j() {
        stopBleScan();
        m14053h();
        setResult(-1);
        Intent intent = new Intent(this.mActivity, DeviceNotFoundActivity.class);
        intent.putExtra(Utils.f3493a, Utils.f3496d);
        startActivity(intent);
        finish();
    }

    public void m13593a(FilterBleDevInfo filterBleDevInfo) {
        GuliLog.tracePrintInfo(TAG, "onScanError");
    }

    public static class aN extends DimPanelFragment {
        private String f9493a;

        protected int inflateLayout() {
            return R.layout.fragment_found_weight_scale;
        }

        public void onCreate(Bundle bundle) {
            super.onCreate(bundle);
            Bundle arguments = getArguments();
            if (arguments != null) {
                this.f9493a = arguments.getString(Constant.aJ);
            }
        }

        public View onCreateView(LayoutInflater layoutInflater, ViewGroup viewGroup, Bundle bundle) {
            View onCreateView = super.onCreateView(layoutInflater, viewGroup, bundle);
            ((TextView) onCreateView.findViewById(R.id.found_weight_value)).setText(this.f9493a);
            return onCreateView;
        }

        protected void onLeftButtonClicked() {
            SearchWeightScaleActivity searchWeightScaleActivity = (SearchWeightScaleActivity) getActivity();
            if (searchWeightScaleActivity != null) {
                searchWeightScaleActivity.m14062b(false);
            }
            dismiss();
        }

        protected void onRightButtonClicked() {
            SearchWeightScaleActivity searchWeightScaleActivity = (SearchWeightScaleActivity) getActivity();
            if (searchWeightScaleActivity != null) {
                searchWeightScaleActivity.m14062b(true);
            }
            dismiss();
        }
    }

    // 得到体重信息并进行显示
    public void m14058a(C3907e c3907e) {
        if (c3907e == null || c3907e.scaleWeightInfo == null || c3907e.btDev == null) {
            GuliLog.m12370d(TAG, "weight Data is null or device is null!");
            return;
        }
        this.mWeightInfo = c3907e.scaleWeightInfo;
        if (this.f9208E == null) {
            this.f9208E = new HashMap();
        }
        if (!this.f9208E.containsKey(c3907e.btDev.getAddress())) {
            this.f9208E.put(c3907e.btDev.getAddress(), C3657a.f18328f);
        }
        GuliLog.tracePrintInfo(TAG, "onEventMainThread, weight = " + this.mWeightInfo.m25499j() + " stable = " + this.mWeightInfo.isStable() + ", isMeasure= " + this.mWeightInfo.m25492c() + ", isFinish = " + this.mWeightInfo.isFinish());
        this.mScaleValue.setText(this.mWeightInfo.m25499j() + C3657a.f18328f);
        this.mScaleSmile.setVisibility(View.GONE);
        // to start the scan, if conditions are satisfied.
        // 1. is stable ture.
        // 2. is finish false.
        if (this.mWeightInfo.isStable() && !this.mWeightInfo.isFinish()) {
            stopBleScan();
            GuliLog.tracePrintInfo(TAG, "broadcasts number = " + this.f9208E.size());
            if (this.f9208E.size() <= f9198c) {
                this.mBleDev = c3907e.btDev;
                m14035a(c3907e.btDev);
            } else if (!this.f9207D) {
                this.mBleDev = c3907e.btDev;
                GuliLog.tracePrintInfo(TAG, "device addr=" + this.mBleDev.getAddress());
                this.mWeightInfoA = this.mWeightInfo;
                Bundle bundle = new Bundle();
                bundle.putString(Constant.aJ, this.mWeightInfo.m25499j() + C3657a.f18328f);
                GuliLog.tracePrintInfo(TAG, "found weight = " + this.mWeightInfo.m25499j());
                DimPanelFragment.showPanel((Activity) this, aN.class, bundle);
                C0668a.m8129a(this.mActivity, "BindScaleConfirmRequest", "MAC", this.mBleDev.getAddress());
                this.f9207D = true;
                C0668a.m8126a(this.mActivity, C0668a.fY);
            }
        }
    }

    class ShowWeightRunnable implements Runnable
    {

        final C3907e thisC3907e;
        final SearchWeightScaleActivity thisSearchWeightScaleActivity;

        ShowWeightRunnable(SearchWeightScaleActivity searchweightscaleactivity, C3907e c3907e)
        {
            super();
            thisSearchWeightScaleActivity = searchweightscaleactivity;
            thisC3907e = c3907e;
        }

        public void run()
        {
            thisSearchWeightScaleActivity.m14058a(thisC3907e);
        }
    }

    public void onScanedDevice(C3907e c3907e, FilterBleDevInfo filterBleDevInfo) {
        GuliLog.tracePrintInfo(TAG, "onScanedDevice");
        if (c3907e == null) {
            GuliLog.tracePrintInfo(TAG, "Adv data is null");
        } else {
            this.mHandler.post(new ShowWeightRunnable(this, c3907e));
        }
    }

    protected void m14060a(boolean z) {
        this.f9225w = z;
        if (this.f9225w) {
            this.mSearchView.setVisibility(View.GONE);
            this.mDevView.setVisibility(View.VISIBLE);
            return;
        }
        this.mSearchView.setVisibility(View.VISIBLE);
        this.mDevView.setVisibility(View.GONE);
    }

    public void m13595b(FilterBleDevInfo filterBleDevInfo) {
    }

    public void m14062b(boolean z) {
        if (z) {
            C0668a.m8129a(this.mActivity, C0708b.av, C0715c.f3775q, this.mBleDev.getAddress());
            this.mBindDevTitle.setText(R.string.pairing);
            m14035a(this.mBleDev);
        } else {
            C0668a.m8129a(this.mActivity, C0708b.au, C0715c.f3775q, this.mBleDev.getAddress());
            startBleScan();
        }
        this.f9207D = false;
    }

    protected void onActivityResult(int i, int i2, Intent intent) {
        GuliLog.tracePrintInfo(TAG, "requestCode =" + i + ", resultCode=" + i2);
        if (i == f9197b) {
            switch (i2) {
                case -1 /*-1*/:
                    this.mHandler.removeMessages(f9200e);
                    this.mHandler.sendEmptyMessageDelayed(f9200e, 60000);//TBD C4125d.f20546g);
                            startBleScan();
                    break;
                case C4220a.f20886i /*0*/:
                    C3247b.m22930a((Context) this, getString(R.string.failed_enable_bt), (int) f9198c).show();
                    finish();
                    break;
            }
        }
        super.onActivityResult(i, i2, intent);
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.search_devices_exit:
                C0668a.m8126a(this.mActivity, C0668a.fU);
                C0668a.m8129a((Context) this, C0708b.an, C0715c.f3772n, Constants.VIA_TO_TYPE_QQ_GROUP);
                setResult(-1);
                finish();
            case R.id.search_devices_not_response:
                m14054i();
            default:
        }
    }

    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView((int) R.layout.activity_search_single_bracelet);
        this.mActivity = this;
        // here we create what we want to find for the scale device
        // 3 key informations
        // 1. the timeout
        // 2. interface for the call back
        // 3. the UUID we are looking for.
        this.mFilterWeightInfo = new C3900g().setTimeout((int) f9203h).m25388a((C1798h) this).setUUID(C3923a.y_).create();
        this.mBtDevList = new ArrayList();
        Intent intent = getIntent();
        if (intent != null) {
            this.f9225w = intent.getBooleanExtra(C4220a.bz, false);
            GuliLog.tracePrintInfo(TAG, "mDevMode = " + this.f9225w);
        } else {
            this.f9225w = false;
        }
        // init  view
        initView();

        // init the message handler and the register receiver for the weight change
        m14033a();

        // set the search view
        m14060a(this.f9225w);

        // disconnect with the weight if any
        m14053h();

        // stop scan
        stopBleScan();

        // to check if the BLE enabled or not
        boolean c = m14043c();
        C0668a.m8129a(this.mActivity, C0708b.ak, C0715c.f3771m, c ? Constants.VIA_TO_TYPE_QQ_GROUP : Constants.VIA_RESULT_SUCCESS);
        if (c) {
            this.mHandler.removeMessages(f9200e);
            this.mHandler.sendEmptyMessageDelayed(f9200e, 60000);
            C0668a.m8126a(this.mActivity, C0708b.ao);

            // start to scan
            startBleScan();
        }
    }

    protected void onDestroy() {
        super.onDestroy();
        stopBleScan();
        unregisterReceiver(this.f9227y);
    }

    protected void onResume() {
        super.onResume();
        if (this.f9208E != null) {
            this.f9208E.clear();
        }
        this.f9207D = false;
    }
}
